package com.example.demo1.Controller;

import com.example.demo1.Entity.User;
import com.example.demo1.commton.Wrapper;
import com.example.demo1.commton.WrapMapper;
import com.example.demo1.dao.userDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class userController {
    
    @Autowired
    private userDao userDao;

    @PostMapping("/register")
    public Wrapper<String> register(@RequestBody User user) {
        if (userDao.checkUsernameExists(user.getUsername())) {
            return WrapMapper.error("注册失败，用户名已经存在");
        }
        
        userDao.insertUser(user);
        return WrapMapper.ok("注册成功");
    }

    @PostMapping("/login")
    public Wrapper<String> login(@RequestBody User loginUser) {
        User user = userDao.getUserByUsername(loginUser.getUsername());
        if (user != null && user.getPassword().equals(loginUser.getPassword())) {
            return WrapMapper.ok("登录成功");
        }
        return WrapMapper.error("登录失败：用户名或密码错误");
    }

    @PostMapping("/addUser")
    public Wrapper<String> addUser(@RequestBody User newUser) {
        if (newUser.getUsername() == null || newUser.getUsername().isEmpty()) {
            return WrapMapper.error("用户名不能为空");
        }

        if (userDao.checkUsernameExists(newUser.getUsername())) {
            return WrapMapper.error("增加失败：用户名已存在");
        }

        userDao.insertUser(newUser);
        return WrapMapper.ok("增加成功");
    }

    @PostMapping("/deleteUser")
    public Wrapper<String> deleteUser(@RequestBody String username) {
        int result = userDao.deleteUser(username);
        if (result > 0) {
            return WrapMapper.ok("删除成功");
        } else {
            return WrapMapper.error("删除失败：未找到用户");
        }
    }

    @GetMapping("/all")
    public Wrapper<List<User>> getAllUser() {
        try {
            List<User> users = userDao.getAllUsers();
            return WrapMapper.ok(users);
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.error("获取用户列表失败");
        }
    }

    @PostMapping("/updateUser")
    public Wrapper<String> updateUser(@RequestBody User updatedUser) {
        if (updatedUser.getUsername() == null || updatedUser.getUsername().isEmpty()) {
            return WrapMapper.error("用户名不能为空");
        }

        int result = userDao.updateUser(updatedUser);
        if (result > 0) {
            return WrapMapper.ok("用户信息更新成功");
        } else {
            return WrapMapper.error("更新失败：未找到用户");
        }
    }

    @GetMapping("/test")
    public Wrapper<String> test() {
        return WrapMapper.ok("API is working!");
    }
}
